package com.czy.owner.ui.order;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.czy.owner.R;
import com.czy.owner.adapter.OrderAdapter;
import com.czy.owner.adapter.ShoppingLikeAapter;
import com.czy.owner.api.GuessYouLikeApi;
import com.czy.owner.api.OrderListApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.GuessYouLikeModel;
import com.czy.owner.entity.OrdersListModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.easyrecycleview.decoration.DividerGridItemDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;
import rx.Observable;

/**
 * Created by wangyang on 2017/5/14 0014.
 * 全部订单
 */

public class AllOrderFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.easy_recycleview)
    EasyRecyclerView recyclerView;
    private OrderAdapter adapter;
    private Handler handler = new Handler();
    private int page = 1;
    private ShoppingLikeAapter shoppingLikeAapter = new ShoppingLikeAapter(getActivity());
    private LinearLayout llOrderFooter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.common_fragment_easyrecycleview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_shopping_strategy_divider_decoration));
        recyclerView.setAdapterWithProgress(adapter = new OrderAdapter(getActivity()));
        adapter.setMore(R.layout.view_more, this);
//        adapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
//            @Override
//            public void onNoMoreShow() {
//
//            }
//
//            @Override
//            public void onNoMoreClick() {
//                adapter.resumeMore();
//            }
//        });

        adapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();

            }
        });
        recyclerView.setRefreshListener(this);

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<OrdersListModel.ListBean>() {
            @Override
            public void onItemClick(View view,int position, OrdersListModel.ListBean model) {
                if (PhoneUtils.isNetworkConnected(getActivity())) {
                    Intent ti = new Intent(getActivity(), OrderDetailActivity.class);
                    ti.putExtra("orderId", model.getUserOrderId());
                    startActivity(ti);
                }

            }
        });
    }

    @Override
    protected void updateViews() {
        onRefresh();
    }


    private void getDataList(final boolean isFirst) {
        OrderListApi orderListApi = new OrderListApi(new HttpOnNextListener<OrdersListModel>() {
            @Override
            public void onNext(OrdersListModel model) {
                if (isFirst) {
                    adapter.clear();
                }
                setDataList(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<OrdersListModel>>() {
                }.getType();
                BaseResultEntity<OrdersListModel> model = gson.fromJson(cache, type);
                setDataList(model.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }


        }, (RxAppCompatActivity) (getContext()), page + "", "all");
        orderListApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        orderListApi.setStoreId(SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        orderListApi.setPageNumber(page + "");
        orderListApi.setPageSize("15");
        orderListApi.setStatus("");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(orderListApi);
    }


    private void setDataList(OrdersListModel model) {
        if (model.getList().size() < 9 && page == 1) {
            adapter.stopMore();
        }
        adapter.addAll(model.getList());

        if(!UserHelper.getInstance().isCloseMall()){
            if (adapter.getAllData().size() == 0) {
                if(shoppingLikeAapter.getAllData().size()==0){
                    adapter.addFooter(new RecyclerArrayAdapter.ItemView() {
                        @Override
                        public View onCreateView(ViewGroup parent) {
                            LayoutInflater inflater = LayoutInflater.from(getActivity());
                            View view = inflater.inflate(R.layout.include_order_like_footer, null);
                            EasyRecyclerView recycleViewLike = (EasyRecyclerView) view.findViewById(R.id.easy_like_recycleview);
                            llOrderFooter = (LinearLayout) view.findViewById(R.id.ll_order_footer);
                            llOrderFooter.setVisibility(View.VISIBLE);
                            recycleViewLike.setAdapter(shoppingLikeAapter = new ShoppingLikeAapter(getActivity()));
//                            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
//                            gridLayoutManager.setSpanSizeLookup(shoppingLikeAapter.obtainGridSpanSizeLookUp(2));
//                            recycleViewLike.setLayoutManager(gridLayoutManager);
//                            recycleViewLike.addItemDecoration(new DividerGridItemDecoration(getActivity()));

                            GridLayoutManager gridLayoutManager1 = new GridLayoutManager(getActivity(), 2);
                            gridLayoutManager1.setSpanSizeLookup(shoppingLikeAapter.obtainGridSpanSizeLookUp(2));
                            recycleViewLike.setLayoutManager(gridLayoutManager1);
//                            recycleViewLike.setNestedScrollingEnabled(false);
                            recycleViewLike.addItemDecoration(new DividerGridItemDecoration(getActivity(),6f,R.drawable.shape_recyclerview_divider_decoration_commen));

                            shoppingLikeAapter.setMore(null, new RecyclerArrayAdapter.OnLoadMoreListener() {
                                @Override
                                public void onLoadMore() {

                                }
                            });
                            getShoppingLikeData();
                            return view;
                        }

                        @Override
                        public void onBindView(View headerView) {
                            ((ViewGroup) headerView).requestDisallowInterceptTouchEvent(true);
                        }
                    });
                }

            }else {
                shoppingLikeAapter.clear();
                if(llOrderFooter!=null){
                    llOrderFooter.setVisibility(View.GONE);
                }
            }
        }else {
            if (adapter.getAllData().size() == 0) {
                recyclerView.setEmptyView(R.layout.order_empty_view);
                recyclerView.showEmpty();
            }
        }

    }

    private void getShoppingLikeData() {
        MyLog.e("yang","AllOrderFragment");
        GuessYouLikeApi guessYouLikeApi = new GuessYouLikeApi(new HttpOnNextListener<GuessYouLikeModel>() {
            @Override
            public void onNext(GuessYouLikeModel model) {
                setShoppingLikeData(model.getList());
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<GuessYouLikeModel>>() {
                }.getType();
                BaseResultEntity<GuessYouLikeModel> cacheList = gson.fromJson(cache, type);
                setShoppingLikeData(cacheList.getData().getList());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) (getContext()), "1");
        guessYouLikeApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        guessYouLikeApi.setPage("1");
        guessYouLikeApi.setSize("20");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(guessYouLikeApi);
    }


    private void setShoppingLikeData(List<GuessYouLikeModel.ListBean> list) {
        shoppingLikeAapter.addAll(list);
        shoppingLikeAapter.notifyDataSetChanged();
        shoppingLikeAapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<GuessYouLikeModel.ListBean>() {
            @Override
            public void onItemClick(View view,int position, GuessYouLikeModel.ListBean data) {
                Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
                intent.putExtra("goodsId", data.getGoodsId());
                intent.putExtra("mFromType", Constants.GOODSSOURCE_OTHER);
                intent.putExtra("mFromTypeId", "0");
                startActivity(intent);
            }
        });
    }


    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getDataList(false);
                MyLog.e("yang", "********************");

            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                page = 1;
                getDataList(true);
            }
        }, 1000);
    }

    @Override
    public void reloadData() {
        //刷新
        if(mIsMulti){
            page = 1;
            getDataList(true);
        }

    }
}
